package com.eliteams.quick4j.core.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2016/4/17.
 */
public class SearchUtil {
    protected static Logger logger = LogManager.getLogger(SearchUtil.class);

    /**
     * 搜索10个结果
     * @param keyWord
     * @return
     */
    public static String searchBaidu10(String keyWord){
        return searchBaidu(keyWord,10);
    }

    /**
     * 发送get数据执行搜索
     * @param keyWord
     * @param count
     * @return
     */
    public static String searchBaidu(String keyWord,int count){
        String url="http://www.baidu.com/s?";
        Map map=new HashMap();
        String wd="";
        try {
            wd = URLEncoder.encode(keyWord,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        map.put("wd", wd);
        map.put("tn","json");
        map.put("rn",count);
        url=url+joinParams(map);
        return sendGet(url);
    }

    /**
     * 连接get的请求参数
     * @param map
     * @return
     */
    public static String joinParams(Map map){
        StringBuilder sb=new StringBuilder();
        for (Object key : map.keySet()) {
            sb.append(key.toString()).append("=").append(map.get(key)).append("&");
        }
        return sb.substring(0,sb.length()-1);
    }
    /**
     * 发送get
     * @param url
     * @return
     */
    public static String sendGet(String url) {
        HttpClient httpclient = new DefaultHttpClient();
        String res = "";
        try {
            HttpGet httpget = new HttpGet(url);
            HttpResponse response = httpclient.execute(httpget);
//获取响应实体
            HttpEntity entity = response.getEntity();
//打印响应状态
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
//打印响应内容
//                System.out.println("Response content: " + EntityUtils.toString(entity));
            }
            res=EntityUtils.toString(entity,"utf-8");
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭连接,释放资源
            httpclient.getConnectionManager().shutdown();
            return res;
        }
    }
    /**
     * 发送post请求到指定地址
     * @param url 请求地址
     * @param parameters json String
     * @return responseBody
     */
    public static String postJson(String url, String parameters){
        HttpPost method = new HttpPost(url);
        HttpClient httpClient = new DefaultHttpClient();
        //设置超时
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000);
        int status = 0;

        String body = null;
        if (method != null & parameters != null
                && !"".equals(parameters.trim())) {
            try {
                // 建立一个NameValuePair数组，用于存储欲传送的参数
                method.addHeader("Content-type", "application/json; charset=utf-8");
                method.setHeader("Accept", "application/json");
                method.setEntity(new StringEntity(parameters, Charset.forName("UTF-8").toString()));

                HttpResponse response = httpClient.execute(method);

                int statusCode = response.getStatusLine().getStatusCode();

                logger.info("statusCode:" + statusCode);
                if (statusCode != HttpStatus.SC_OK) {
                    logger.error("Method failed:" + response.getStatusLine());
                    status = 1;
                }
                // Read the response body
                body = EntityUtils.toString(response.getEntity());
            } catch (IOException e) {
                logger.error("短信发送失败:网络异常,parameters="+parameters);
                // 网络错误
                status = 3;
            } finally {
                logger.info("调用接口状态：" + status);
            }
        }
        return body;
    }

}
